<template>
  <div class="organizer-home">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <h1 class="welcome-title">
          欢迎回来，{{ userStore.userInfo?.name }}！
        </h1>
        <p class="welcome-subtitle">
          今天是 {{ formatDate(new Date(), 'YYYY年MM月DD日') }}，
          {{ getTimeGreeting() }}！让我们一起创造精彩的活动体验。
        </p>
      </div>
      <div class="welcome-actions">
        <el-button type="primary" size="large" @click="goToCreateActivity">
          <el-icon><Plus /></el-icon>
          创建新活动
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalActivities }}</div>
              <div class="stat-label">总活动数</div>
            </div>
            <el-icon class="stat-icon total"><Calendar /></el-icon>
          </div>
          <div class="stat-trend">
            <span class="trend-text">较上月</span>
            <span :class="['trend-value', stats.activitiesTrend >= 0 ? 'positive' : 'negative']">
              {{ stats.activitiesTrend >= 0 ? '+' : '' }}{{ stats.activitiesTrend }}%
            </span>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalRegistrations }}</div>
              <div class="stat-label">总报名数</div>
            </div>
            <el-icon class="stat-icon registrations"><Tickets /></el-icon>
          </div>
          <div class="stat-trend">
            <span class="trend-text">较上月</span>
            <span :class="['trend-value', stats.registrationsTrend >= 0 ? 'positive' : 'negative']">
              {{ stats.registrationsTrend >= 0 ? '+' : '' }}{{ stats.registrationsTrend }}%
            </span>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-number">{{ stats.pendingApprovals }}</div>
              <div class="stat-label">待审核</div>
            </div>
            <el-icon class="stat-icon pending"><Clock /></el-icon>
          </div>
          <div class="stat-action">
            <el-button type="primary" size="small" text @click="goToRegistrations">
              立即处理
            </el-button>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-number">{{ stats.averageRating.toFixed(1) }}</div>
              <div class="stat-label">平均评分</div>
            </div>
            <el-icon class="stat-icon rating"><Star /></el-icon>
          </div>
          <div class="stat-extra">
            <el-rate
              :model-value="stats.averageRating"
              disabled
              size="small"
              show-score
              text-color="#ff9900"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <!-- 左侧内容 -->
      <el-col :xs="24" :lg="16">
        <!-- 最近活动 -->
        <el-card class="recent-activities-card">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><Calendar /></el-icon>
                <span>最近活动</span>
              </div>
              <el-button type="primary" text @click="goToActivities">
                查看全部
              </el-button>
            </div>
          </template>
          
          <div v-if="loadingActivities" class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>
          
          <div v-else-if="recentActivities.length === 0" class="empty-container">
            <el-empty description="暂无活动" :image-size="80">
              <el-button type="primary" @click="goToCreateActivity">
                创建第一个活动
              </el-button>
            </el-empty>
          </div>
          
          <div v-else class="activities-list">
            <div 
              v-for="activity in recentActivities" 
              :key="activity.id"
              class="activity-item"
              @click="goToActivityDetail(activity.id)"
            >
              <div class="activity-info">
                <h4 class="activity-title">{{ activity.title }}</h4>
                <div class="activity-meta">
                  <span class="meta-item">
                    <el-icon><Clock /></el-icon>
                    {{ formatDate(activity.startTime, 'MM-DD HH:mm') }}
                  </span>
                  <span class="meta-item">
                    <el-icon><Location /></el-icon>
                    {{ activity.location }}
                  </span>
                  <span class="meta-item">
                    <el-icon><User /></el-icon>
                    {{ activity.currentParticipants || 0 }}/{{ activity.maxParticipants || '不限' }}
                  </span>
                </div>
              </div>
              <div class="activity-status">
                <el-tag :type="getActivityStatus(activity).type" size="small">
                  {{ getActivityStatus(activity).text }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
        
        <!-- 数据图表 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><DataAnalysis /></el-icon>
                <span>活动数据趋势</span>
              </div>
              <el-radio-group v-model="chartPeriod" size="small">
                <el-radio-button label="week">最近7天</el-radio-button>
                <el-radio-button label="month">最近30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          
          <div class="chart-container">
            <div v-if="loadingChart" class="loading-container">
              <el-skeleton :rows="4" animated />
            </div>
            <div v-else class="chart-placeholder">
              <!-- 这里可以集成图表库如 ECharts -->
              <div class="chart-mock">
                <div class="chart-title">活动报名趋势</div>
                <div class="chart-content">
                  <div class="chart-bars">
                    <div 
                      v-for="(item, index) in chartData" 
                      :key="index"
                      class="chart-bar"
                      :style="{ height: `${item.value * 2}px` }"
                    >
                      <div class="bar-value">{{ item.value }}</div>
                    </div>
                  </div>
                  <div class="chart-labels">
                    <span v-for="(item, index) in chartData" :key="index" class="chart-label">
                      {{ item.label }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧边栏 -->
      <el-col :xs="24" :lg="8">
        <!-- 待办事项 -->
        <el-card class="todo-card">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><Bell /></el-icon>
                <span>待办事项</span>
              </div>
              <el-badge :value="todoItems.length" :hidden="todoItems.length === 0" />
            </div>
          </template>
          
          <div v-if="todoItems.length === 0" class="empty-container">
            <el-empty description="暂无待办事项" :image-size="60" />
          </div>
          
          <div v-else class="todo-list">
            <div 
              v-for="item in todoItems" 
              :key="item.id"
              class="todo-item"
              :class="item.priority"
              @click="handleTodoClick(item)"
            >
              <div class="todo-content">
                <div class="todo-title">{{ item.title }}</div>
                <div class="todo-desc">{{ item.description }}</div>
                <div class="todo-time">{{ formatDate(item.dueTime, 'MM-DD HH:mm') }}</div>
              </div>
              <div class="todo-priority">
                <el-tag :type="getPriorityType(item.priority)" size="small">
                  {{ getPriorityText(item.priority) }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
        
        <!-- 最新反馈 -->
        <el-card class="feedback-card">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><ChatDotRound /></el-icon>
                <span>最新反馈</span>
              </div>
              <el-button type="primary" text @click="goToFeedbacks">
                查看全部
              </el-button>
            </div>
          </template>
          
          <div v-if="loadingFeedbacks" class="loading-container">
            <el-skeleton :rows="2" animated />
          </div>
          
          <div v-else-if="recentFeedbacks.length === 0" class="empty-container">
            <el-empty description="暂无反馈" :image-size="60" />
          </div>
          
          <div v-else class="feedback-list">
            <div 
              v-for="feedback in recentFeedbacks" 
              :key="feedback.id"
              class="feedback-item"
              @click="goToFeedbackDetail(feedback.id)"
            >
              <div class="feedback-content">
                <div class="feedback-activity">{{ feedback.activity?.title }}</div>
                <div class="feedback-text">{{ feedback.content }}</div>
                <div class="feedback-meta">
                  <el-rate
                    :model-value="feedback.rating"
                    disabled
                    size="small"
                  />
                  <span class="feedback-time">{{ formatDate(feedback.createTime, 'MM-DD') }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        
        <!-- 快捷操作 -->
        <el-card class="quick-actions-card">
          <template #header>
            <div class="header-title">
              <el-icon><Operation /></el-icon>
              <span>快捷操作</span>
            </div>
          </template>
          
          <div class="quick-actions">
            <div class="action-item" @click="goToCreateActivity">
              <el-icon class="action-icon"><Plus /></el-icon>
              <span class="action-text">创建活动</span>
            </div>
            <div class="action-item" @click="goToRegistrations">
              <el-icon class="action-icon"><Tickets /></el-icon>
              <span class="action-text">审核报名</span>
            </div>
            <div class="action-item" @click="goToStatistics">
              <el-icon class="action-icon"><DataAnalysis /></el-icon>
              <span class="action-text">查看统计</span>
            </div>
            <div class="action-item" @click="exportData">
              <el-icon class="action-icon"><Download /></el-icon>
              <span class="action-text">导出数据</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { formatDate, getActivityStatus } from '@/utils'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import {
  Plus,
  Calendar,
  Tickets,
  Clock,
  Star,
  Location,
  User,
  DataAnalysis,
  Bell,
  ChatDotRound,
  Operation,
  Download
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

const loadingActivities = ref(false)
const loadingFeedbacks = ref(false)
const loadingChart = ref(false)
const chartPeriod = ref('week')

const stats = reactive({
  totalActivities: 0,
  totalRegistrations: 0,
  pendingApprovals: 0,
  averageRating: 0,
  activitiesTrend: 0,
  registrationsTrend: 0
})

const recentActivities = ref([])
const recentFeedbacks = ref([])
const todoItems = ref([])
const chartData = ref([])

const getTimeGreeting = () => {
  const hour = new Date().getHours()
  if (hour < 6) return '夜深了，注意休息'
  if (hour < 12) return '早上好'
  if (hour < 18) return '下午好'
  return '晚上好'
}

const getPriorityType = (priority) => {
  const typeMap = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return typeMap[priority] || 'info'
}

const getPriorityText = (priority) => {
  const textMap = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return textMap[priority] || priority
}

const loadStats = async () => {
  try {
    const response = await api.get('/organizer/stats')
    const data = response.data.data
    
    Object.assign(stats, data)
    
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const loadRecentActivities = async () => {
  try {
    loadingActivities.value = true
    
    const response = await api.get('/organizer/activities', {
      params: { size: 5, sort: 'createTime,desc' }
    })
    
    recentActivities.value = response.data.data?.data || []
    
  } catch (error) {
    console.error('加载最近活动失败:', error)
  } finally {
    loadingActivities.value = false
  }
}

const loadRecentFeedbacks = async () => {
  try {
    loadingFeedbacks.value = true
    
    const response = await api.get('/organizer/feedbacks', {
      params: { size: 3, sort: 'createTime,desc' }
    })
    
    recentFeedbacks.value = response.data.data?.data || []
    
  } catch (error) {
    console.error('加载最新反馈失败:', error)
  } finally {
    loadingFeedbacks.value = false
  }
}

const loadTodoItems = async () => {
  try {
    const response = await api.get('/organizer/todos')
    todoItems.value = response.data.data || []
  } catch (error) {
    console.error('加载待办事项失败:', error)
  }
}

const loadChartData = async () => {
  try {
    loadingChart.value = true
    
    const response = await api.get('/organizer/chart-data', {
      params: { period: chartPeriod.value }
    })
    
    chartData.value = response.data.data || []
    
    // 模拟数据
    if (chartData.value.length === 0) {
      chartData.value = [
        { label: '周一', value: 12 },
        { label: '周二', value: 19 },
        { label: '周三', value: 8 },
        { label: '周四', value: 25 },
        { label: '周五', value: 16 },
        { label: '周六', value: 22 },
        { label: '周日', value: 14 }
      ]
    }
    
  } catch (error) {
    console.error('加载图表数据失败:', error)
  } finally {
    loadingChart.value = false
  }
}

const goToCreateActivity = () => {
  router.push('/organizer/activities/create')
}

const goToActivities = () => {
  router.push('/organizer/activities')
}

const goToRegistrations = () => {
  router.push('/organizer/registrations')
}

const goToFeedbacks = () => {
  router.push('/organizer/feedbacks')
}

const goToStatistics = () => {
  router.push('/organizer/statistics')
}

const goToActivityDetail = (id) => {
  router.push(`/organizer/activities/${id}`)
}

const goToFeedbackDetail = (id) => {
  router.push(`/organizer/feedbacks/${id}`)
}

const handleTodoClick = (item) => {
  // 根据待办事项类型跳转到相应页面
  switch (item.type) {
    case 'approval':
      goToRegistrations()
      break
    case 'feedback':
      goToFeedbacks()
      break
    default:
      ElMessage.info('功能开发中...')
  }
}

const exportData = () => {
  ElMessage.info('数据导出功能开发中...')
}

onMounted(() => {
  loadStats()
  loadRecentActivities()
  loadRecentFeedbacks()
  loadTodoItems()
  loadChartData()
})
</script>

<style scoped>
.organizer-home {
  max-width: 1400px;
  margin: 0 auto;
}

.welcome-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px;
  border-radius: 12px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-content {
  flex: 1;
}

.welcome-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 12px 0;
}

.welcome-subtitle {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
  line-height: 1.5;
}

.welcome-actions {
  margin-left: 20px;
}

.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  height: 120px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  font-size: 32px;
  opacity: 0.3;
}

.stat-icon.total {
  color: #409eff;
}

.stat-icon.registrations {
  color: #67c23a;
}

.stat-icon.pending {
  color: #e6a23c;
}

.stat-icon.rating {
  color: #f56c6c;
}

.stat-trend,
.stat-action,
.stat-extra {
  margin-top: 8px;
  font-size: 12px;
}

.trend-text {
  color: #909399;
}

.trend-value.positive {
  color: #67c23a;
}

.trend-value.negative {
  color: #f56c6c;
}

.recent-activities-card,
.chart-card {
  margin-bottom: 20px;
}

.todo-card,
.feedback-card,
.quick-actions-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.loading-container,
.empty-container {
  padding: 20px;
  text-align: center;
}

.activities-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.activity-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.activity-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.activity-info {
  flex: 1;
}

.activity-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.activity-meta {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #606266;
}

.chart-container {
  height: 300px;
  padding: 20px 0;
}

.chart-mock {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-title {
  text-align: center;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}

.chart-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.chart-bars {
  display: flex;
  align-items: end;
  justify-content: space-around;
  height: 200px;
  padding: 0 20px;
}

.chart-bar {
  width: 30px;
  background: linear-gradient(to top, #409eff, #79bbff);
  border-radius: 4px 4px 0 0;
  position: relative;
  min-height: 10px;
  display: flex;
  align-items: end;
  justify-content: center;
}

.bar-value {
  position: absolute;
  top: -20px;
  font-size: 12px;
  color: #606266;
  font-weight: 600;
}

.chart-labels {
  display: flex;
  justify-content: space-around;
  padding: 10px 20px 0;
}

.chart-label {
  font-size: 12px;
  color: #909399;
}

.todo-list,
.feedback-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-left: 4px solid #e4e7ed;
  background: #f8f9fa;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  transition: all 0.3s ease;
}

.todo-item:hover {
  background: #f0f9ff;
}

.todo-item.high {
  border-left-color: #f56c6c;
}

.todo-item.medium {
  border-left-color: #e6a23c;
}

.todo-item.low {
  border-left-color: #909399;
}

.todo-content {
  flex: 1;
}

.todo-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.todo-desc {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.todo-time {
  font-size: 12px;
  color: #909399;
}

.feedback-item {
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.feedback-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.feedback-activity {
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
  font-size: 14px;
}

.feedback-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.feedback-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.feedback-time {
  font-size: 12px;
  color: #909399;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.action-icon {
  font-size: 24px;
  color: #409eff;
}

.action-text {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-section {
    flex-direction: column;
    gap: 20px;
    text-align: center;
    padding: 24px;
  }
  
  .welcome-title {
    font-size: 24px;
  }
  
  .welcome-actions {
    margin-left: 0;
  }
  
  .activity-meta {
    flex-direction: column;
    gap: 8px;
  }
  
  .chart-bars {
    padding: 0 10px;
  }
  
  .chart-bar {
    width: 20px;
  }
  
  .quick-actions {
    grid-template-columns: 1fr;
  }
}
</style>